package convert.converter;


import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class csv_to_yaml {

    public static void main(String[] args) {
        String csvFilePath = "src/resource/csv/input_example.csv";
        String yamlFilePath = "src/resource/yaml/output.yaml";

        convertCSVToYAML(csvFilePath, yamlFilePath);
    }

    public static void convertCSVToYAML(String csvFilePath, String yamlFilePath) {
        try {
            CSVReader csvReader = new CSVReader(new FileReader(csvFilePath));
            List<String[]> rows = csvReader.readAll();
            csvReader.close();

            List<String> headers = new ArrayList<>();
            List<Map<String, String>> data = new ArrayList<>();

            // Extract headers
            if (!rows.isEmpty()) {
                String[] headerRow = rows.get(0);
                for (String header : headerRow) {
                    headers.add(header.trim());
                }
            }

            // Extract data rows
            for (int i = 1; i < rows.size(); i++) {
                String[] rowData = rows.get(i);
                Map<String, String> rowMap = new LinkedHashMap<>();
                for (int j = 0; j < headers.size() && j < rowData.length; j++) {
                    String value = rowData[j].trim();
                    rowMap.put(headers.get(j), value);
                }
                data.add(rowMap);
            }

            // Write data to YAML file
            FileWriter writer = new FileWriter(yamlFilePath);
            Yaml yaml = createYamlObject();
            yaml.dump(data, writer);

            writer.close();

            System.out.println("CSV to YAML conversion completed successfully.");
        } catch (IOException | CsvException e) {
            e.printStackTrace();
        }
    }

    private static Yaml createYamlObject() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // Use block style for better readability

        return new Yaml(options);
    }
}
